package com.juzhi.dvrapp.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.juzhi.dvrapp.R;
import com.juzhi.dvrapp.bean.Device;
import com.juzhi.dvrapp.bean.DeviceModel;
import com.juzhi.dvrapp.bean.DeviceUser;
import com.juzhi.dvrapp.bean.LzyResponse;
import com.juzhi.dvrapp.callback.DialogCallback;
import com.juzhi.dvrapp.manager.DeviceManager;
import com.juzhi.dvrapp.utils.Config;
import com.juzhi.dvrapp.utils.T;
import com.juzhi.dvrapp.utils.Urls;
import com.juzhi.dvrapp.utils.ValidatorUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import butterknife.BindView;
import butterknife.OnClick;


public class DeviceAddRemoteActivity extends BaseAcitivity {


    public static final int REQUEST_CODE = 111;
    @BindView(R.id.activity_add_remote_device_name)
    EditText mEditDeviceName;
    @BindView(R.id.activity_add_remote_device_ssid)
    EditText mEditSsid;
    @BindView(R.id.activity_add_remote_device_username)
    EditText mEditUserName;
    @BindView(R.id.activity_add_remote_device_password)
    EditText mEditPwd;
    @BindView(R.id.activity_input_device_showpwd)
    Button mShowPwdBtn;

    private boolean isClickShowPwd = false;
    private DeviceManager deviceManager;
    private Device device;
    private DeviceModel deviceModel;
    private AlertDialog alertDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_device_add_remote;
    }

    @Override
    protected void initView() {
        initHeaderView();
        setTitleText(getResources().getString(R.string.activity_add_remote_device));
        setFunctionImg(getResources().getDrawable(R.drawable.title_scan));
        deviceManager = DeviceManager.getDeviceManager(this);
    }


    @Override
    protected void function() {
        super.function();
        Intent intent = new Intent(getApplication(), CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    mEditSsid.setText(result);
                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(DeviceAddRemoteActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }


    @OnClick({R.id.activity_input_device_showpwd, R.id.activity_add_remote_device_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_input_device_showpwd:
                showPwd();
                break;
            case R.id.activity_add_remote_device_btn:
                commitDevice(view);
                break;
        }
    }

    private void showPwd() {
        isClickShowPwd = !isClickShowPwd;
        if (isClickShowPwd) {
            mShowPwdBtn.setText(getResources().getString(R.string.input_device_hidepwd));
            mEditPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            mShowPwdBtn.setText(getResources().getString(R.string.input_device_showpwd));
            mEditPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

    private void commitDevice(View view) {

        String deviceName = mEditDeviceName.getText().toString().trim();
        String ssid = mEditSsid.getText().toString().trim();
        String userName = mEditUserName.getText().toString().trim();
        String password = mEditPwd.getText().toString().trim();

        if (ValidatorUtils.isSpechars(userName) || ValidatorUtils.isSpechars(password)) {
            T.showShort(getResources().getString(R.string.user_pwd_no_show));
            return;
        }

        if (TextUtils.isEmpty(deviceName)) {
            T.showShort(getResources().getString(R.string.input_camera_name));
            return;
        } else if (TextUtils.isEmpty(ssid)) {
            T.showShort(getResources().getString(R.string.input_camera_id));
            return;
        } else if (TextUtils.isEmpty(userName)) {
            T.showShort(getResources().getString(R.string.input_camera_username));
            return;
        } else if (TextUtils.isEmpty(password)) {
            T.showShort(getResources().getString(R.string.input_camera_password));
            return;
        }

        if (deviceManager.getRemoteDevice().size() >= 10) {
            T.showShort(getResources().getString(R.string.add_camer_no_add));
            return;
        }


        deviceModel = new DeviceModel(null, deviceName, ssid, userName, password, 1);

        for (Device dev : deviceManager.getRemoteDevice()) {
            if (dev.getDeviceModel().getSsid().equals(deviceModel.getSsid())) {
                T.showShort(getResources().getString(R.string.input_camera_all_include));
                return;
            }
        }

        loginHttpRequest(view);
    }

    private void loginHttpRequest(View view) {
        OkGo.<LzyResponse<DeviceUser>>post(Urls.URL_DEVICELOGIN)
                .tag(DeviceAddRemoteActivity.this)
                .params(Config.DEVICEID, deviceModel.getSsid())
                .params(Config.USERNAME, deviceModel.getUserName())
                .params(Config.PASSWORD, deviceModel.getPassword())
                .execute(new DialogCallback<LzyResponse<DeviceUser>>(DeviceAddRemoteActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<DeviceUser>> response) {
                        int mStatus = response.body().status;
                        if (mStatus == Config.DEVICE_RESULT_CONNECTING) {
                            T.showShort(getResources().getString(R.string.string_status_connect_timeout_error));
                        } else if (mStatus == Config.DEVICE_RESULT_EXCEPTIONS) {
                            T.showShort(getResources().getString(R.string.string_status_connect_httpservice_error));
                        } else if (mStatus == Config.DEVICE_RESULT_ERROR_SSID) {
                            T.showShort(getResources().getString(R.string.string_status_connect_ssid_error));
                        } else if (mStatus == Config.DEVICE_RESULT_ERROR_PWD) {
                            T.showShort(getResources().getString(R.string.string_status_connect_login_errer));
                        } else if (mStatus == Config.DEVICE_RESULT_ERROR_LOGIN) {
                            showConstraintLogin();
                        } else if (mStatus == Config.DEVICE_RESULT_SUCCESS) {
                            device = new Device();
                            device.setDeviceModel(deviceModel);
                            device.setStatus(mStatus);
                            device.setSystemLevel(response.body().result.getType());
                            device.setUserId(response.body().result.getId());
                            deviceManager.saveDevice(device);

                            getDeviceInfo(device);
                        } else {
                            T.showShort(getResources().getString(R.string.string_adddevice_error));
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<DeviceUser>> response) {
                        super.onError(response);
                        T.showShort(getResources().getString(R.string.string_adddevice_error));
                    }
                });
    }



    private void showConstraintLogin() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(getResources().getString(R.string.string_hide));
        dialog.setMessage(getResources().getString(R.string.string_connect_haslogin));
        dialog.setCancelable(false);
        dialog.setPositiveButton(getResources().getString(R.string.string_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                OkGo.<LzyResponse<DeviceUser>>post(Urls.URL_DEVICECONSTRAINTLOGIN)
                        .tag(DeviceAddRemoteActivity.this)
                        .params(Config.DEVICEID, deviceModel.getSsid())
                        .params(Config.USERNAME, deviceModel.getUserName())
                        .execute(new DialogCallback<LzyResponse<DeviceUser>>(DeviceAddRemoteActivity.this) {
                            @Override
                            public void onSuccess(Response<LzyResponse<DeviceUser>> response) {
                                LzyResponse<DeviceUser> body = response.body();
                                if (response.body().status == Config.DEVICE_RESULT_SUCCESS) {
                                    device = new Device();
                                    device.setDeviceModel(deviceModel);
                                    device.setStatus(body.status);
                                    device.setSystemLevel(body.result.getType());
                                    deviceManager.saveDevice(device);

                                    Intent intent = new Intent(DeviceAddRemoteActivity.this, DeviceInfoActivity.class);
                                    intent.putExtra(Config.SSID, deviceModel.getSsid());
                                    startActivity(intent);
                                    finish();
                                }
                            }

                            @Override
                            public void onError(Response<LzyResponse<DeviceUser>> response) {
                                super.onError(response);
                                T.showShort(getResources().getString(R.string.string_adddevice_error));
                            }
                        });

            }
        });
        dialog.setNegativeButton(getResources().getString(R.string.string_cancel), null);

        alertDialog = dialog.create();
        alertDialog.getWindow().setWindowAnimations(R.style.pickerview_dialogAnim);
        alertDialog.getWindow().setBackgroundDrawableResource(R.drawable.loading_bg);
        alertDialog.show();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (alertDialog != null) {
            if (alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            alertDialog = null;
        }
    }
}
